package cn.xinfei.xdecision.data.thread;

import cn.xinfei.xdecision.common.model.datax.consts.VariableConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;

@Slf4j
public class MDCThreadPoolTaskScheduler extends ThreadPoolTaskScheduler {

    @Override
    public void execute(Runnable task) {
        ScheduledExecutorService executor = this.getScheduledExecutor();
        try {
            log.info("execute...");
            executor.execute(wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "did not accept task: " + task, ex);
        }
    }

    @Override
    public Future<?> submit(Runnable task) {
        ScheduledExecutorService executor = this.getScheduledExecutor();
        try {
            log.info("submit...");
            return executor.submit(wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "did not accept task: " + task, ex);
        }
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        ScheduledExecutorService executor = this.getScheduledExecutor();

        try {
            log.info("submit...");
            return executor.submit(wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException ex) {
            throw new TaskRejectedException("Executor [" + executor + "did not accept task: " + task, ex);
        }

    }

    /**
     * Wrap callable
     *
     * @param <T>     parameter
     * @param task    task
     * @param context context
     * @return the callable
     */
    private <T> Callable<T> wrap(final Callable<T> task, final Map<String, String> context) {
        return () -> {
            Map<String, String> previous = MDC.getCopyOfContextMap();
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
                if (StringUtils.isBlank(MDC.get(VariableConst.TRACE_ID))) {
                    String traceId = UUID.randomUUID().toString().replace("-", "") + "_" + "SCH";
                    MDC.put(VariableConst.TRACE_ID, traceId);
                }
            }
            try {
                return task.call();
            } finally {
                if (previous == null) {
                    MDC.clear();
                } else {
                    MDC.setContextMap(previous);
                }
            }
        };
    }

    /**
     * Wrap runnable
     *
     * @param runnable runnable
     * @param context  context
     * @return the runnable
     */
    private Runnable wrap(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            Map<String, String> previous = MDC.getCopyOfContextMap();
            if (context == null) {
                MDC.clear();
            } else {
                MDC.setContextMap(context);
                if (StringUtils.isBlank(MDC.get(VariableConst.TRACE_ID))) {
                    String traceId = UUID.randomUUID().toString().replace("-", "") + "_" + "SCH";
                    MDC.put(VariableConst.TRACE_ID, traceId);
                }
            }
            try {
                runnable.run();
            } finally {
                if (previous == null) {
                    MDC.clear();
                } else {
                    MDC.setContextMap(previous);
                }
            }
        };
    }
}
